package com.xingda.packing.dmss.common;

import org.apache.commons.math3.distribution.ChiSquaredDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.util.CombinatoricsUtils;

public class RangeUtils {
    public static double succeed_mu_factor(double t_min, double t_max, Double p_mu, double p_sigma, int empty_drawing_num,
                                           int cache_capacity) {
        NormalDistribution nd = new NormalDistribution();
        double tn_min = (t_min - p_mu) / p_sigma * Math.sqrt(empty_drawing_num);
        double tn_max = (t_max - p_mu) / p_sigma * Math.sqrt(empty_drawing_num);
        double sfactor = nd.cumulativeProbability(tn_max) - nd.cumulativeProbability(tn_min);
        long nchance = 0;
        for (int i = 0; i <= empty_drawing_num; i++) {
            nchance += (i > cache_capacity ? 0 : CombinatoricsUtils.binomialCoefficient(cache_capacity, i));
        }
        return 1 - Math.pow(1 - sfactor, nchance);
    }

    public static double succeed_sigma_factor(double t_sigma, double p_sigma, int empty_drawing_num, int cache_capacity) {
        ChiSquaredDistribution csd = new ChiSquaredDistribution(empty_drawing_num);
        double sfactor = csd.cumulativeProbability(Math.pow(t_sigma, 2) / Math.pow(p_sigma, 2) * empty_drawing_num);
        long nchance = 0;
        for (int i = 0; i <= empty_drawing_num; i++) {
            nchance += (i > cache_capacity ? 0 : CombinatoricsUtils.binomialCoefficient(cache_capacity, i));
        }
        return 1.0 - Math.pow(1 - sfactor, nchance);
    }
}

